package net.mmgg.android.bm;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class InitActivity extends Activity {
	private final String ip_ = "112.124.58.97";
	private final String ctx_ = "/bd/";
	private final String id_ = "shenzhen";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		final Config cfg = (Config) getApplication();

		setContentView(R.layout.activity_init);

		Button configButton = (Button) this.findViewById(R.id.config_btn);
		final EditText config_url = (EditText) this.findViewById(R.id.config_url);
		final EditText config_code = (EditText) this.findViewById(R.id.config_code);
		config_url.setText(ip_);
		config_code.setText(id_);
		configButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				String ip = config_url.getText().toString();
				String code = config_code.getText().toString();
				if ("".equals(ip) || "".equals(code)) {
					Toast.makeText(getApplicationContext(), "请正确填写相关参数!", Toast.LENGTH_LONG).show();
					return;
				}
				String ipRegx = "^(([0-2]*[0-9]+[0-9]+)\\.([0-2]*[0-9]+[0-9]+)\\.([0-2]*[0-9]+[0-9]+)\\.([0-2]*[0-9]+[0-9]+))$";
				Pattern p = Pattern.compile(ipRegx);
				Matcher m = p.matcher(ip);
				if (m.matches()) {
					cfg.setUrl("http://" + ip + ctx_);
					cfg.setCode(code);
					Intent mainIntent = new Intent(InitActivity.this, MainActivity.class);
					InitActivity.this.finish();
					startActivity(mainIntent);
					finish();
				} else {
					Toast.makeText(getApplicationContext(), "服务器地址不正确!", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

}
